class RadchecksController < ApplicationController
  before_action :set_radcheck, only: [:show, :edit, :update, :destroy]
  before_action :set_radcheckable, only: [:index, :new, :edit, :create, :update, :destroy]

  # GET /radchecks
  # GET /radchecks.json
  def index
    @radchecks = @radcheckable.radchecks.all
  end

  # GET /radchecks/1
  # GET /radchecks/1.json
  def show
    @user_id = params[:user_id]
  end

  # GET /radchecks/new
  def new
    @radcheck = @radcheckable.radchecks.new
  end

  # GET /radchecks/1/edit
  def edit
  end

  # POST /radchecks
  # POST /radchecks.json
  def create
    @radcheck = @radcheckable.radchecks.new(radcheck_params)
    @radcheck.username = @radcheckable.class.name == 'User' ? @radcheckable.username : @radcheckable.token

    respond_to do |format|
      if @radcheck.save
        format.html { redirect_to [@radcheckable, @radcheck], notice: 'Radcheck was successfully created.' }
        format.json { render action: 'show', status: :created, location: @radcheck }
      else
        format.html { render action: 'new' }
        format.json { render json: @radcheck.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /radchecks/1
  # PATCH/PUT /radchecks/1.json
  def update
    respond_to do |format|
      if @radcheck.update(radcheck_params)
        format.html { redirect_to polymorphic_path([@radcheckable, @radcheck]), notice: 'Radcheck was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @radcheck.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /radchecks/1
  # DELETE /radchecks/1.json
  def destroy
    @radcheck.destroy
    respond_to do |format|
      format.html { redirect_to polymorphic_path([@radcheckable, :radchecks]) }
      format.json { head :no_content }
    end
  end

  private
    # polymorphic resource 
    def set_radcheckable
      if params[:user_id]
        @radcheckable = User.find(params[:user_id])
      elsif params[:device_id]
        @radcheckable = Device.find(params[:device_id])
      end
    end

    # Use callbacks to share common setup or constraints between actions.
    def set_radcheck
      @radcheck = set_radcheckable.radchecks.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def radcheck_params
      params.require(:radcheck).permit(:op, :value, :attr)
    end
end
